package com.atguigu.eduservice.controller.front;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.commonutils.ordervo.CourseWebVoOrder;
import com.atguigu.eduservice.client.OrderClient;
import com.atguigu.eduservice.pojo.EduCourse;
import com.atguigu.eduservice.pojo.chapter.ChapterVo;
import com.atguigu.eduservice.pojo.frontvo.CourseFrontVo;
import com.atguigu.eduservice.pojo.frontvo.CourseWebVo;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduCourseService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/eduservice/coursefront")
@CrossOrigin
public class CourseFrontController {
    //远程调用，功能是查询是否存在该用户订单表中的订单状态
    @Autowired
    private OrderClient orderClient;

    @Autowired
    private EduChapterService chapterService;
    @Autowired
    private EduCourseService courseService;
    //条件查询带分页查询课程
    @PostMapping("getFrontCourseList/{page}/{limit}")
    public R getFrontCourseList(@PathVariable long page, @PathVariable long limit,
                                @RequestBody(required = false) CourseFrontVo courseFrontVo){
        //进行分页查询
        Page <EduCourse> pageCourse = new Page(page,limit);
        Map<String,Object> map =  courseService.getCourseFrontList(pageCourse,courseFrontVo);
        return R.ok().data(map);
    }
    //课程的详情的方法
    @GetMapping("getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request){
        //根据课程id编写sql语句进行查询
        CourseWebVo courseWebVo = courseService.getBaseCourseInfo(courseId);
        //查询改课程所有章节和小节
        List<ChapterVo> chapterVoList = chapterService.getChapterVideoByCourseId(courseId);
        //根据课程id查询章节和小节部分
        //根据课程id查询当前课程是否已经支付过了
        String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(request);
        boolean buyCourse = orderClient.isBuyCourse(courseId, memberIdByJwtToken);

        return R.ok().data("courseWebVo",courseWebVo).data("chapterVideoList",chapterVoList).data("isBuy",buyCourse);
    }
    //根据课程id查询课程信息
    @PostMapping("getCourseInfoOrder/{id}")
    public CourseWebVoOrder getCourseInfoOrder(@PathVariable String id){
        CourseWebVo baseCourseInfo = courseService.getBaseCourseInfo(id);
        CourseWebVoOrder courseWebVoOrder = new CourseWebVoOrder();
        BeanUtils.copyProperties(baseCourseInfo,courseWebVoOrder);
        //返回一个新的order
        return courseWebVoOrder;
    }

}

